const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
    let {
        optType,
        param
    } = event;
    switch (optType) {
        case "queryPage": {
            return queryPageData(param.currentPage - 1, param.classifyId);
        }
        case "getById": {
            incLikeCount(param.resId, 1);
            return getDetailById(param.resId);
        }
        case "incCount":{
            return incLikeCount(param.resId, param.num);
        }
    }

};


// 分页查询列表数据
async function queryPageData(currentPage, classifyId) {
    let whereClassifyId = {};
    if (classifyId != "0") {
        whereClassifyId = {
            classifyId: dbCmd.eq(classifyId)
        };
    }
    return await db.collection("aiExtra_resources").where(whereClassifyId).field({
            _id: true,
            title: true,
            headPic: true,
            label: true,
            likeCount: true,
            createTime: true
        })
        .orderBy("topping", "asc").orderBy("likeCount", "desc").limit(10).skip(currentPage * 10).get();
};


// 获取详情
async function getDetailById(resId) {
    return await db.collection("aiExtra_resources").doc(resId).get();
};


// 增加热度，点击查看详情热度+1，收藏热度+5
async function incLikeCount(resId, hotCount) {
    return await db.collection("aiExtra_resources").doc(resId).update({
      likeCount: dbCmd.inc(hotCount)
    });
};
